package com.bmoblistview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Student> studentArrayList;
    private IOnChangeListener listener;

    public StuAdapter(Context context, ArrayList<Student> studentArrayList, IOnChangeListener listener) {
        this.context = context;
        this.studentArrayList = studentArrayList;
        this.listener = listener;
    }

    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return studentArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null) {
            view = LayoutInflater.from(context).inflate(
                    R.layout.stu_item, parent, false);

            StuViewHolder viewHolder = new StuViewHolder();
            viewHolder.tvName = view.findViewById(R.id.tv_name);
            viewHolder.tvAge = view.findViewById(R.id.tv_age);
            viewHolder.tvGender = view.findViewById(R.id.tv_gender);
            viewHolder.iv_del = view.findViewById(R.id.iv_del);
            view.setTag(viewHolder);
        }

        final Student student = studentArrayList.get(position);
        StuViewHolder viewHolder = (StuViewHolder) view.getTag();
        viewHolder.tvName.setText(student.getName());
        viewHolder.tvAge.setText(String.valueOf(student.getAge()));
        viewHolder.tvGender.setText(student.getGender());
        viewHolder.iv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.del(student.getObjectId());
            }
        });
        return view;
    }

    public void notifyDataChanged(ArrayList<Student> studentArrayList) {
        this.studentArrayList = studentArrayList;
        notifyDataSetChanged();
    }
}
